<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/6/26 0026
// +----------------------------------------------------------------------
// | Description:
// +----------------------------------------------------------------------

namespace app\admin\controller;


use app\admin\model\AdminUser;
use app\admin\service\ExcelService;
use app\admin\validate\CheckAdminUser;
use app\common\controller\AdminBaseController;
use app\common\service\FormBuilder as Form;
use think\Exception;
use think\facade\Route;

class Admin extends AdminBaseController
{
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new AdminUser();
    }

    /**
     * @return string|\think\response\Json
     * @throws \Exception
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/7/2 0002
     * @describe:修改密码
     */
    public function changPass()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            try {
                //当前密码
                $pass = AdminUser::where("id", self::$admin_info['id'])->value("password");

                if (!password_very($data['oldpassword'], $pass)) {
                    return parent::JsonReturn("当前密码错误", 0);
                }
                unset($data['oldpassword']);

                $checkUser = new CheckAdminUser();
                $check = $checkUser->scene("Pass")->check($data);
                if (!$check) {
                    return parent::JsonReturn($checkUser->getError(), 0);
                }
                $data['id'] = (int)self::$admin_info['id'];

                unset($data['repassword']);
                //密码加密
                $data['password'] = password($data['password']);

                return $this->model->doAll($data);

            } catch (\Exception $exception) {
                return parent::JsonReturn($exception->getMessage(), 0);
            }
        }

        $f = [];
        $f[] = Form::input('oldpassword', '当前密码：')->required("请输入当前密码")->placeholder("请输入当前密码")->col(13);
        $f[] = Form::input('password', '新密码：')->placeholder("请输入新密码")->required("请输入新密码")->col(13);
        $f[] = Form::input('repassword', '确认密码：')->placeholder("请输入确认密码")->required("请输入确认密码")->col(13);
        $f[] = Form::hidden("__token__", token());
        $form = Form::make_post_form('修改我的密码', $f, Route::buildUrl('changPass'),6);
        $this->assign(compact('form'));
        return $this->fetch();
    }


    /**
     * @return string|\think\response\Json
     * @throws \FormBuilder\exception\FormBuilderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:基本资料
     */
    public function baseData()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            $checkUser = new CheckAdminUser();
            try {
                $check = $checkUser->check($data);
                if (!$check) {
                    return parent::JsonReturn($checkUser->getError(), 0);
                }
                $res = AdminUser::where(['username' => "" . $data['username'] . ""])->where("id", "<>", $data['id'])->find();
                if ($res) {
                    return parent::JsonReturn($data['username'] . "该用户名已存在", 0);
                }
                return $this->model->doAll($data);

            } catch (\Exception $exception) {
                return parent::JsonReturn($exception->getMessage(), 0);
            }
        }

        $info=AdminUser::find(self::$admin_info['id'])->toArray();
        $f = [];
        $f[] = Form::hidden("id", $info['id']);
        $f[] = Form::frameImageOne("avatar","头像：",Route::buildUrl('admin/AttachMents/getImagesOne', array('fodder' => 'avatar')),$info['avatar'])->icon('image')->height("500px")->width('60%')->spin(0);
        $f[] = Form::input('username', '用户名：', $info['username'])->required("请输入管理员用户名");
        $f[] = Form::input('nickname', '管理员昵称：', $info['nickname'])->placeholder("请输入管理员昵称");
        $f[] = Form::input('phone', '手机号：', $info['phone'])->placeholder("请输入手机号");
        $f[] = Form::input('email', '邮箱：', $info['email'])->placeholder("请输入管理员邮箱");
        $f[] = Form::date("birthday","生日：",$info['birthday'])->placeholder("出生日期")->info("管理员出生日期");
        $f[] = Form::radio('sex', '性别：', $info['sex'])->options([['label' => '男', 'value' => 0], ['label' => '女', 'value' => 1],['label' => '保密', 'value' => 2]]);
        $f[] = Form::radio('status', '状态：', $info['status'])->options([['label' => '禁止', 'value' => 0], ['label' => '正常', 'value' => 1]]);
        //$f[] = Form::uploadImageOne("avastar","dadasd：",Route::buildUrl('admin/AttachMents/getImagesOne', array('fodder' => 'avastar')));
        $f[] = Form::hidden("__token__", token());
        $form = Form::make_post_form('修改我的资料', $f, Route::buildUrl('baseData'),6);
        $this->assign(compact('form'));
        return $this->fetch();

    }

    /**
     * @param AdminUser $adminUser
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:数据导出
     */
    public function export(AdminUser $adminUser){
        $param=$this->request->post();
        $where=[];
        $order = 'id desc';
        if (isset($param['username']) && $param['username'] != '') {
            $where[] = ['username', 'like', "%" . $param['username'] . "%"];
        }

        if (!empty($param['isAsc']) && !empty($param['orderByColumn'])){
            $order="{$param['orderByColumn']} {$param['isAsc']}";
        }

        if (!empty($param['status'])){
            $status=(int)$param['status']-1;
            $where[] = ['status', '=', $status];
        }

        if (!empty($param['beginTime']) && !empty($param['endTime'])){
            $where[] = ['create_time', 'between', [strtotime($param['beginTime']),strtotime($param['endTime'])]];
        }
        $result=$adminUser->where($where)->order($order)->select()->toArray();
        if (empty($result)){
            return parent::JsonReturn("根据条件未查询到数据",0);
        }

        $arr=[];
        foreach ($result as $k=>$v){
            $arr[]=[
                $v['id'],$v['username'],$v['nickname'],$adminUser::getSexName($v['sex']),$adminUser::getStatusName($v['status'])
                ,$v['phone'],$v['email'],$v['birthday'],$v['logins'],$v['create_time']
            ];
        }
        $filename= ExcelService::setExcelHeader(['ID','用户名','昵称','性别','状态','手机号','邮箱','生日','登录次数','时间'])
            ->setExcelTile('管理员列表数据', '管理员数据',date('Y-m-d H:i:s',time()))
            ->setExcelContent($arr)
            ->ExcelReturn();
        return parent::JsonReturn($filename);
    }


    /**
     * @return string|\think\response\Json
     * @throws \FormBuilder\exception\FormBuilderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:添加编辑
     */
    public function addAdmin()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            $checkUser = new CheckAdminUser();
            try {
                $check = $checkUser->check($data);
                if ($check==false) {
                    return parent::JsonReturn($checkUser->getError(), 0);
                }
                if (isset($data['id'])) {
                    if (!empty($data['password']) && !empty($data['repassword'])) {
                        $data['password'] = password($data['password']);
                    } else {
                        unset($data['password']);
                    }
                    unset($data['repassword']);
                } else {
                    $res = AdminUser::where(['username' => "" . $data['username'] . ""])->find();
                    if ($res) {
                        return parent::JsonReturn($data['username'] . "该用户名已存在", 0);
                    }
                    $data['password'] = password($data['password']);
                    unset($data['repassword']);
                }

                return $this->model->doAll($data);

            } catch (Exception $exception) {
                return parent::JsonReturn($exception->getMessage(), 0);
            }
        }
        $f = [];
        $f[] = Form::frameImageOne("avatar","用户头像：",Route::buildUrl('admin/AttachMents/getImagesOne', array('fodder' => 'avatar')))->icon('image')->width('60%')->height("400px")->spin(0);
        $f[] = Form::input('username', '用户名：')->required("请输入管理员用户名");
        $f[] = Form::input('nickname', '管理员昵称：')->placeholder("请输入管理员昵称");
        $f[] = Form::input('password', '登录密码：')->type("password")->required("请输入登录密码");
        $f[] = Form::input('repassword', '确认密码：')->type("password")->required("请输入登录密码");
        $f[] = Form::input('phone', '手机号：')->placeholder("请输入手机号");
        $f[] = Form::input('email', '邮箱：')->placeholder("请输入管理员邮箱");
        $f[] = Form::date("birthday","生日：")->placeholder("出生日期")->info("管理员出生日期");
        $f[] = Form::radio('sex', '性别：',0)->options([['label' => '男', 'value' => 0], ['label' => '女', 'value' => 1],['label' => '保密', 'value' => 2]]);
        $f[] = Form::radio('status', '状态：',1)->options([['label' => '禁止', 'value' => 0], ['label' => '正常', 'value' => 1]]);
        $f[] = Form::hidden("__token__", token());
        $form = Form::make_post_form('添加管理员', $f, Route::buildUrl('addAdmin'));
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }


    /**
     * @return string
     * @throws \FormBuilder\exception\FormBuilderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:编辑
     */
    public function editAdmin(){
        $id = $this->request->param("id/d",0);//父id
        $info = AdminUser::find($id);
        $f = [];
        $f[] = Form::hidden("id", $info['id']);
        $f[] = Form::frameImageOne("avatar","用户头像：",Route::buildUrl('admin/AttachMents/getImagesOne', array('fodder' => 'avatar')),$info['avatar'])->icon('image')->width('60%')->height("400px")->spin(0);
        $f[] = Form::input('username', '用户名：', $info['username'])->required("请输入管理员用户名");
        $f[] = Form::input('nickname', '管理员昵称：', $info['nickname'])->placeholder("请输入管理员昵称");
        $f[] = Form::input('password', '登录密码：')->info("不填密码则不修改密码！！！")->type("password");
        $f[] = Form::input('repassword', '确认密码：')->info("不填密码则不修改密码！！！")->type("password");
        $f[] = Form::input('phone', '手机号：', $info['phone'])->placeholder("请输入手机号");
        $f[] = Form::input('email', '邮箱：', $info['email'])->placeholder("请输入管理员邮箱");
        $f[] = Form::date("birthday","生日：",$info['birthday'])->placeholder("出生日期")->info("管理员出生日期");
        $f[] = Form::radio('sex', '性别：', $info['sex'])->options([['label' => '男', 'value' => 0], ['label' => '女', 'value' => 1],['label' => '保密', 'value' => 2]]);
        $f[] = Form::radio('status', '状态：', $info['status'])->options([['label' => '禁止', 'value' => 0], ['label' => '正常', 'value' => 1]]);
        $f[] = Form::hidden("__token__", token());
        $form = Form::make_post_form('修改管理员资料', $f, Route::buildUrl('addAdmin'));
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }




}